#pragma warning(disable: 4005)

#include "Win32DebugDisplay.h"
#include "NeroCore\NMemoryManager.h"
#include "DirectX\Device.h"
#include "Win32Input.h"

using namespace System;

Win32DebugDisplay::Win32DebugDisplay(void)
	:XPosition(10.0f),
	 YPosition(20.0f),
	 mCurrentEventIndex(0),
	 mIsRendering(false)
{
}

Win32DebugDisplay::~Win32DebugDisplay(void)
{
	mScreenObjects.clear();
}

bool Win32DebugDisplay::Initialize(D3DXMATRIX baseMatrix)
{
	mBaseMatrix = baseMatrix;
	mIsRendering = true;
	return true;
}

void Win32DebugDisplay::Update(float gameTime)
{
	for(unsigned int i = 0; i < mScreenObjects.size(); i++)
	{
		mScreenObjects[i]->text.Update(gameTime);
	}

	ProcessInput();
}

void Win32DebugDisplay::Render()
{
	if(mIsRendering)
	{
		Graphics::D3DDevice* device = GetPlatform()->GetDevice()->As<Graphics::D3DDevice>();

		//Turn off the Z buffer to begin all 2D rendering.
		device->TurnZBufferOff();
		// Turn on the alpha blending before rendering the text.
		device->TurnOnAlphaBlending();
	
		for(unsigned int i = 0; i < mScreenObjects.size(); i++)
		{
			mScreenObjects[i]->text.Render();
		}

		// Turn off alpha blending after rendering the text.
		device->TurnOffAlphaBlending();
		// Turn the Z buffer back on now that all 2D rendering has completed.
		device->TurnZBufferOn();
	}
}


void Win32DebugDisplay::SetDebugText(int id, int x_pos, int y_pos, const char* format, ... )
{
	bool found = false;
	int index = 0;

	va_list argList;
	va_start(argList, format);

	const unsigned int MAX_CHARS = 1023;
	static char buffer[MAX_CHARS + 1];
	memset(buffer, 0, sizeof(buffer));
	vsnprintf_s(buffer, _countof(buffer), _TRUNCATE, format, argList);

	Graphics::D3DDevice* device = GetPlatform()->GetDevice()->As<Graphics::D3DDevice>();

	for(unsigned int i = 0; i < mScreenObjects.size(); i++)
	{
		if(mScreenObjects[i]->ScreenID == id)
		{
			found = true;
			index = i;
		}
	}

	if(found)
	{
		mScreenObjects[index]->text.SetText(x_pos, y_pos, buffer);
	}
	else
	{
		ScreenObject* newScreenObj = MY_NEW(Memory::HID_Rendering, "Screen Object") ScreenObject();
		newScreenObj->ScreenID = id;
		newScreenObj->text.Initialize(device->GetWindowsSettings().WindowHandle,
								    device->GetResolutionInfo().ScreenWidth, 
								    device->GetResolutionInfo().ScreenHeight,
									mBaseMatrix);
		newScreenObj->text.SetText(x_pos, y_pos, buffer);
		mScreenObjects.push_back(newScreenObj);
	}
}

void Win32DebugDisplay::ProcessInput()
{
	if(GetInput()->IsKeyDown(VK_F1))
	{
		mIsRendering = true;
	}
	if(GetInput()->IsKeyDown(VK_F2))
	{
		mIsRendering = false;
	}
}